package com.bluegalaxy.nhb.snservice.service.ck.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bluegalaxy.nhb.service.AssembleService;
import com.bluegalaxy.nhb.snservice.common.utils.DateUtil;
import com.bluegalaxy.nhb.snservice.common.utils.SqlTableUtil;
import com.bluegalaxy.nhb.snservice.common.utils.StringUtil;
import com.bluegalaxy.nhb.snservice.dao.UserGroupMapper;
import com.bluegalaxy.nhb.snservice.dao.UserTagsMapper;
import com.bluegalaxy.nhb.snservice.domain.constant.CkConstant;
import com.bluegalaxy.nhb.snservice.domain.enums.BaseUserEnum;
import com.bluegalaxy.nhb.snservice.domain.vo.BootstrapTablePage;
import com.bluegalaxy.nhb.snservice.domain.vo.api.R;

import com.bluegalaxy.nhb.snservice.service.ck.UserTagsService;
import com.bluegalaxy.nhb.snservice.service.execute.ExecuteService;
import com.bluegalaxy.nhb.snservice.service.execute.XxService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("UserTagsService")
public class UserTagsServiceImpl implements UserTagsService {
    @Autowired
    private UserGroupMapper userGroupMapper;
    @Autowired
    private UserTagsMapper userTagsMapper;
    @Autowired
    private ExecuteService executeService;
    @Autowired
    private XxService xxService;

    @Resource
    private AssembleService assembleService;

    private final static String tagsArray = "tagsLevelList";


    @Override
    public R findUsersById(JSONObject param) {
        String tableId = param.getString("tableId");
        if (StringUtil.isEmpty(tableId)){
            return R.fail("");
        }
        String groupType = param.getString("tagsLevel");
        String groupTypeName = param.getString("tagsLevelName");

        int current = param.getInteger("current")==null? 0 :param.getInteger("current");
        int pageSize = param.getInteger("pageSize")==null? 10 :param.getInteger("pageSize");
//        current = current == 1?0:current;
        int startPage = current == 0?0:(current - 1) * pageSize;

        List<Map<String,Object>> attrList = xxService.selectUserAttribute();
//        PageAutoDialect.registerDialectAlias("clickhouse", MySqlDialect.class);
        PageHelper.startPage(current,pageSize);
        List<Map<String,Object>> list = userTagsMapper.selectByTableName(tableId,startPage,pageSize,attrList,groupType,groupTypeName);
        Integer totalCount = userTagsMapper.countByTableName(tableId,groupType,groupTypeName);
//        PageInfo<Map<String,Object>> pageInfo = new PageInfo<>(list);
        BootstrapTablePage tablePage = new BootstrapTablePage();
        tablePage.setRows(list);
        tablePage.setTotal(totalCount.longValue());
        return R.data(tablePage);
    }

    @Override
    public R createUsers(JSONObject param) {
        String tableName = StringUtil.isEmpty(param.getString("tableId"))?SqlTableUtil.getTagName():param.getString("tableId");
        String tableType = StringUtil.isEmpty(param.getString("tableType"))?"ADD":param.getString("tableType");
        String dt = StringUtil.isEmpty(param.getString("dt"))? DateUtil.getNowYYYYMMDD() :param.getString("dt");
        if ("ADD".equals(tableType)){
            boolean flag = executeService.createTable(tableName, BaseUserEnum.TAGS.name());
            if (!flag){
                return R.fail("创建用户标签错误");
            }
        }
        int dtCount = userTagsMapper.countByDt(tableName,dt);
        if (dtCount > 0){
            return R.fail("该日期【"+dt+"】下用户数据已存在。");
        }

        JSONArray paramTagsArray = param.getJSONArray(tagsArray);
        String globalStr = param.getString("globalStr");
        String attributeStr = param.getString("attributeStr");
        String actionStr = param.getString("actionStr");
        String orderStr = param.getString("orderStr");
        int listSize = 0;
        List<Map<String,Object>> levelList = new ArrayList<>();
        for (int i=0;i<paramTagsArray.size();i++){
            JSONObject paramObj = paramTagsArray.getJSONObject(i);
            String tagsLevel = paramObj.getString("tagsLevel");
            String levelName = paramObj.getString("levelName");
            paramObj.put("globalStr",globalStr);
            paramObj.put("attributeStr",attributeStr);
            paramObj.put("actionStr",actionStr);
            paramObj.put("orderStr",orderStr);
            String sql = assembleService.assembleSql(paramObj, CkConstant.ARRAY);
            List<String> list = userGroupMapper.selectBySql(sql);
            if (!list.isEmpty()){
                listSize += list.size();
                userTagsMapper.insertBatch(tableName,list,tagsLevel,levelName,dt);
            }
            Map<String,Object> levelMap = new HashMap<>();
            levelMap.put("tagsLevel",tagsLevel);
            levelMap.put("levelName",levelName);
            levelMap.put("levelCount",list==null?0:list.size());
            levelList.add(levelMap);
        }
        Map<String,Object> res = new HashMap<>();
        res.put("total",listSize);
        res.put("levelData",levelList);

        return R.data(res);
    }


    @Override
    public R countUsers(JSONObject param) {
        JSONArray paramTagsArray = param.getJSONArray(tagsArray);
        String globalStr = param.getString("globalStr");
        String attributeStr = param.getString("attributeStr");
        String actionStr = param.getString("actionStr");
        String orderStr = param.getString("orderStr");
        int sumResult = 0;
        List<Map<String,Object>> levelList = new ArrayList<>();
        for (int i=0;i<paramTagsArray.size();i++){
            JSONObject paramObj = paramTagsArray.getJSONObject(i);
            String tagsLevel = paramObj.getString("tagsLevel");
            String levelName = paramObj.getString("levelName");
            paramObj.put("globalStr",globalStr);
            paramObj.put("attributeStr",attributeStr);
            paramObj.put("actionStr",actionStr);
            paramObj.put("orderStr",orderStr);
            String sql = assembleService.assembleSql(paramObj, CkConstant.COUNT);
            int result = userGroupMapper.countBySql(sql);
            Map<String,Object> levelMap = new HashMap<>();
            levelMap.put("tagsLevel",tagsLevel);
            levelMap.put("levelName",levelName);
            levelMap.put("levelCount",result);
            levelList.add(levelMap);
            sumResult += result;
        }
        Map<String,Object> res = new HashMap<>();
        res.put("total",sumResult);
        res.put("levelData",levelList);


        return R.data(res);
    }

    @Override
    public R findTagsByUser(List<String> tableList, String uId) {
        List<String>  res = userTagsMapper.findTagsByUser(tableList,uId);
        return R.data(res);
    }
}
